//
//  UserSettingController.m
//  CoolTennisBall
//
//  Created by Coollang on 16/8/25.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "UserSettingController.h"
#import "UserGroup.h"
#import "UserArrowItem.h"
#import "UserPersonalDetailVC.h"
#import "UserEquipController.h"
#import "TennisSetWebViewController.h"
#import "CommunicationManager.h"
#import "BTHandler.h"
#import "SportViewController.h"
#import "UserLabelItem.h"
#import "UserExperienceVC.h"


static NSString * const kFeedbackSegue = @"kUserFeedbackSegue";
static NSString * const kWebViewSegue = @"UserWebViewSegue";
static NSString * const kShareSegue = @"UserShareSegue";
static NSString * const kAboutUsSegue = @"UserAboutUsSegue";

static NSString * const kQuickStart = @"http://appserv.coollang.com/TennisViewController/goTennis";
static NSString * const kIssue = @"http://appserv.coollang.com/TennisViewController/faq";
static NSString * const kIssue_en = @"http://appserv.coollang.com/TennisViewController/faqEn";
static NSString * const kIssue_HD = @"http://appserv.coollang.com/TennisViewController/faq_HD";
NSString * const kShop  = @"http://item.jd.com/10360261551.html";
NSString * const kEnShop = @"http://www.coollang-asia.com";
NSString * const kAboutUs = @"http://appserv.coollang.com/WebJumpController/tennisHomePage";
NSString * const kEnAboutUs = @"http://appserv.coollang.com/WebJumpController/tennisHomePageEn";
NSString *const kAboutUs_HD = @"https://detail.tmall.com/item.htm?id=536578823524";

@interface UserSettingController ()
@property (copy, nonatomic) NSString *url;
@property (copy, nonatomic) NSString *webViewTitle;

@property (nonatomic, strong) User *user;

@end

@implementation UserSettingController {
    BOOL _isChinese;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.user = [User getLastUser];
    
    self.tableView.rowHeight = 44;
    
    self.title = NSLocalizedString(@"Settings", nil);
    
    [self loadData];
    [self setTabelViewFooterView];
    
    _isChinese = [NSBundle currentLanguageIsChinese];

}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.user = [User getLastUser];
    [self.tableView reloadData];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:kWebViewSegue]) {
        TennisSetWebViewController *controller = segue.destinationViewController;
        controller.url = self.url;
        controller.title = self.webViewTitle;
    }
}

- (void)loadData {
    
    __weak typeof(self) weakSelf = self;
//    第一组
    UserGroup *group0 = [[UserGroup alloc] init];
    
    UserArrowItem *item0_0 = [UserArrowItem itemWithIcon:@"user_infro" andTitle:NSLocalizedString(@"Personal Data", nil) andTarget:nil];
    [item0_0 setBlock:^{
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"UserCenter" bundle:nil];
        UserPersonalDetailVC *personalVC = [sb instantiateViewControllerWithIdentifier:@"UserPersonalDetailVC"];
        
        [weakSelf.navigationController pushViewController:personalVC animated:YES];
        
    }];
    
    UserArrowItem *item0_1 = [UserArrowItem itemWithIcon:@"user_equiq" andTitle:NSLocalizedString(@"My Equipment", nil) andTarget:[UserEquipController class]];
    UserArrowItem *item0_2 = [UserArrowItem itemWithIcon:@"user_exprience" andTitle:NSLocalizedString(@"My Experience", nil) andTarget:[UserExperienceVC class]];
    
    [group0.items addObjectsFromArray:@[item0_0, item0_1, item0_2]];
    [self.groups addObject:group0];
    
//    第二组
    UserGroup *group1 = [[UserGroup alloc] init];
    
    UserArrowItem *item1_0 = [UserArrowItem itemWithIcon:@"user_quick" andTitle:NSLocalizedString(@"How to Use", nil) andTarget:nil];
    
    [item1_0 setBlock:^{
        [weakSelf openQuickGuide];
    }];
    
    UserArrowItem *item1_1 = [UserArrowItem itemWithIcon:@"user_issue" andTitle:NSLocalizedString(@"FAQ", nil)
        andTarget:nil];
    
    [item1_1 setBlock:^{
        [weakSelf FrequentlyAskedQuestions];
    }];
    
    UserArrowItem *item1_2 = [UserArrowItem itemWithIcon:@"user_aboutUs" andTitle:NSLocalizedString(@"About Us", nil) andTarget:nil];
    [item1_2 setBlock:^{
        [weakSelf aboutUs];
    }];
    switch (self.user.userDevice.oemType) {
        case OemTypeOrignal:{
            [group1.items addObjectsFromArray:@[item1_0, item1_1, item1_2]];
            [self.groups addObject:group1];
        }
            break;
        case OemTypeHD:{
            [group1.items addObjectsFromArray:@[item1_0, item1_1, item1_2]];
            [self.groups addObject:group1];
        }
            break;
        case OemTypeTS:{
            
        }
            break;
        case OemTypeT5:{
            
        }
            break;
            
    }

//    第三组
    UserGroup *group2 = [[UserGroup alloc] init];
    
    UserArrowItem *item2_0 = [UserArrowItem itemWithIcon:@"user_reset" andTitle:NSLocalizedString(@"Factory Reset", nil) andTarget:nil];
    [item2_0 setBlock:^{
        [weakSelf showResetAlertView];
    }];
    
    [group2.items addObject:item2_0];
    [self.groups addObject:group2];
    

    
//    第四组
    UserGroup *group3 = [[UserGroup alloc] init];
    
    UserArrowItem *item3_0 = [UserArrowItem itemWithIcon:@"user_share" andTitle:@"邀请好友" andTarget:nil];
    [item3_0 setBlock:^{
        [weakSelf performSegueWithIdentifier:kShareSegue sender:nil];
    }];
    
    UserArrowItem *item3_1 = [UserArrowItem itemWithIcon:@"user_feedbeek_app" andTitle:NSLocalizedString(@"Feedback", nil)
        andTarget:nil];
    [item3_1 setBlock:^{
       [weakSelf performSegueWithIdentifier:kFeedbackSegue sender:nil];
    }];
    
 
    UserLabelItem *item3_2 = [UserLabelItem itemWithIcon:@"user_id" labelItemWithTitle:NSLocalizedString(@"User ID", nil) andValue:[User getLastUser].userInforItem.userID];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appCurVersion = infoDictionary[@"CFBundleShortVersionString"];
    
    UserLabelItem *item3_3 = [UserLabelItem itemWithIcon:@"user_version" labelItemWithTitle:[NSString stringWithFormat:NSLocalizedString(@"Version: %@", nil),appCurVersion] andValue:nil];
    
    if (_isChinese) {
        [group3.items addObjectsFromArray:@[item3_0, item3_1, item3_2, item3_3]];
    }else {
         [group3.items addObjectsFromArray:@[item3_1, item3_2, item3_3]];
    }
    
    
    [self.groups addObject:group3];

}


#pragma mark - 对应cell的跳转
/**  快速入门 */
- (void)openQuickGuide
{
    if ([User getLastUser].userDevice.oemType == OemTypeOrignal) {
        UIStoryboard *quickGuideStoryboard = [UIStoryboard storyboardWithName:@"QuickGuide" bundle:nil];
        UIViewController *controller = [quickGuideStoryboard instantiateViewControllerWithIdentifier:@"QuickGuideViewController"];
        [self.navigationController pushViewController:controller animated:YES];
    }else {
        // 跳转到海德的快速入门
        UIStoryboard *quickGuideStoryboard = [UIStoryboard storyboardWithName:@"HDQuickGuide" bundle:nil];
        UIViewController *controller = [quickGuideStoryboard instantiateViewControllerWithIdentifier:@"HDQuickGuideViewController"];
        [self.navigationController pushViewController:controller animated:YES];
        
    }
}
/** 常见问题 */
- (void)FrequentlyAskedQuestions {
    if (_isChinese) {
        if ([User getLastUser].userDevice.oemType == OemTypeOrignal) {
            self.url = kIssue;
        }else if([User getLastUser].userDevice.oemType == OemTypeHD) {
            self.url = kIssue_HD;
        }
    } else {
        if ([User getLastUser].userDevice.oemType == OemTypeOrignal) {
            self.url = kIssue_en;
        }else if([User getLastUser].userDevice.oemType == OemTypeHD) {
            self.url = kIssue_HD;
        }
    }
    self.webViewTitle = NSLocalizedString(@"FAQ", nil);
    [self performSegueWithIdentifier:kWebViewSegue sender:nil];
    
}
/** 关于我们 */
- (void)aboutUs {
    if ([User getLastUser].userDevice.oemType == OemTypeOrignal) {
        if (_isChinese) {
            self.url = kAboutUs;
            self.webViewTitle = NSLocalizedString(@"About Us", nil);
        } else {
            self.url = kEnAboutUs;
            self.webViewTitle = NSLocalizedString(@"About Us", nil);
        }
        [self performSegueWithIdentifier:kWebViewSegue sender:nil];
    }else if([User getLastUser].userDevice.oemType == OemTypeHD) {
        self.url = kAboutUs_HD;
        self.webViewTitle = NSLocalizedString(@"About Us", nil);
        [self performSegueWithIdentifier:kWebViewSegue sender:nil];
    }
}

#pragma mark - 重置设备
- (void)showResetAlertView
{
    if (![CommunicationManager shareInstance].isPeripheralConnectedWithoutAlertView) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Please Connect the Device", nil) inView:self.view];
        return;
    }
    FUIAlertView *alert = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Restore Device to Factory Settings?", nil)
                                                      message:NSLocalizedString(@"Restoring factory settings will clear all device information and delete today's records. Continue?", nil)
                                                     delegate:nil
                                            cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
                                            otherButtonTitles:NSLocalizedString(@"Ok", nil), nil];
    [alert customizeAppearance];
    alert.onOkAction = ^{
        [[CommunicationManager shareInstance] performOperationType:OperationTypeResetDevice object:nil completionBlock:^(BOOL success, id feedbackData) {
            if (success) {
                [BTHandler handleResetData:feedbackData withCompletion:^(BOOL successful) {
                    if (successful) {
                        [MBProgressHUD showSuccessHudInView:self.view message:NSLocalizedString(@"Success", nil) afterDelay:1];
                    }else{
                        [MBProgressHUD showFailHudInView:self.view message:NSLocalizedString(@"Fail", nil) afterDelay:1];
                    }
                }];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:SportViewControllerDeleteTodayDataNotification object:nil];
                });
            }else{
                [MBProgressHUD showFailHudInView:self.view message:NSLocalizedString(@"Fail", nil) afterDelay:1];
            }
        }];
    };
    [alert show];
}



#pragma mark - 退出登录
- (void)setTabelViewFooterView {
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, kAutoHei(124))];
    self.tableView.tableFooterView = footerView;
    
    UIButton *button = [[UIButton alloc] init];
    
    button.frame = CGRectMake(0, 30, kYFScreenWidth, kAutoHei(44));
    
    [footerView addSubview:button];
    [button addTarget:self action:@selector(logoutButttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    footerView.backgroundColor = [UIColor colorWithHex:0xf3f3f3];
    
    [button setTitle:NSLocalizedString(@"Log out", nil) forState:UIControlStateNormal];
    [button setTitleColor:kOrangeColor forState:UIControlStateNormal];
    button.titleLabel.font = SanFranciscoFont(16);
    [button setBackgroundColor:[UIColor whiteColor]];
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    // 添加分割线
    UIView *topLine = [[UIView alloc] initWithFrame:CGRectMake(0,button.frame.origin.y - 0.5, kYFScreenWidth, 0.5)];
    topLine.backgroundColor = kLineBackgroundColor;
    [footerView addSubview:topLine];
    
    UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(button.frame), kYFScreenWidth, 0.5)];
    bottomLine.backgroundColor = kLineBackgroundColor;
    [footerView addSubview:bottomLine];
    
}
- (void)logoutButttonClick:(UIButton *)button {
    
    [[CommunicationManager shareInstance] disconnectThePeripheralWithCompletionBlock:^(BOOL success) {
        
    }];
    
    [DataModel setAutoLogin:NO];
    [self.tabBarController dismissViewControllerAnimated:YES completion:nil];
}


@end
